package com.xiaohudie.SGGJUC;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @Author xiao hu die
 * @Date 2022/3/8 23:28
 * @Version 1.0
 */
/**ReadWriteLock的效果与ConcurrentHashMap
 * 的鲜果是一样的
 * 独占锁就是写锁
 * 共享锁就是读锁*/
public class TestReadWritelock {
    public static void main(String[] args) {
       /* MyReadWriteLock myReadWriteLock = new MyReadWriteLock();
        for (int i = 0; i <5 ; i++) {
            final int a =i;
        new Thread(()->{
           myReadWriteLock.setHashMap(String.valueOf(a),String.valueOf(a));
        },"AA").start();}
        for (int i = 0; i <5 ; i++) {
            final int a =i;
            new Thread(()->{
                myReadWriteLock.getHashMap(String.valueOf(a));
            },"BB").start();}
    }*/
        MyReadWriteLock2 myReadWriteLock2 = new MyReadWriteLock2();
        for (int i = 0; i < 15; i++) {
            final int a =i;
            new Thread(()->{
                myReadWriteLock2.setHashMap(String.valueOf(a),String.valueOf(a));
            },"AA").start();
        }
        for (int i = 0; i < 15; i++) {
            final int a =i;
            new Thread(()->{
                myReadWriteLock2.getHashMap(String.valueOf(a));
            },"BB").start();
        }
    }

    class MyReadWriteLock {
        private volatile HashMap<String, Object> hashMap = new HashMap<>();
        /**
         * 加入读写锁
         */
        private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

        /**
         * 写方法
         */
        public void setHashMap(String key, String value) {
            try {
                readWriteLock.writeLock().lock();
                hashMap.put(key, value);
                System.out.println("写入KEY" + key + "写入VALUE" + value);
            } finally {
                readWriteLock.writeLock().unlock();
            }
        }

        /**
         * 读方法
         */
        public void getHashMap(String key) {
            try {
                readWriteLock.readLock().lock();
                Object o = hashMap.get(key);
                System.out.println(o);
            } finally {
                readWriteLock.readLock().unlock();
            }
        }
    }

    static class MyReadWriteLock2 {
        private volatile Map<String, String> hashMap = new ConcurrentHashMap<>();

        /**
         * 写方法
         */
        public void setHashMap(String key, String value) {
            hashMap.put(key, value);
            System.out.println("写入KEY" + key + "写入VALUE" + value);
        }

        /**
         * 读方法
         */
        public void getHashMap(String key) {
            Object o = hashMap.get(key);
            System.out.println(o);
        }
    }
}

